﻿using System.Collections.Generic;
using System.Data.Objects;

namespace Commons
{
    /// <summary>
    /// 用于存放过滤参数,比如一个是名称,一个是值,等价于sql中的Parameters
    /// </summary>
    public class FilterParam
    {
        public FilterParam(string name, object value)
        {
            Name = name;
            Value = value;
        }

        public string Name { get; set; }
        public object Value { get; set; }

        /// <summary>
        /// 转化为ObjectParameter可变参数
        /// </summary>
        /// <returns></returns>
        public ObjectParameter ToObjParam()
        {
            var param = new ObjectParameter(Name, Value);
            return param;
        }

        /// <summary>
        /// 为查询语句添加参数
        /// </summary>
        /// <param name="commandText">查询命令</param>
        /// <returns></returns>
        public static string AddParameters(string commandText, IEnumerable<FilterParam> listfilter)
        {
            foreach (var param in listfilter)
            {
                if (param.Value.IsValidInput())
                {
                    commandText = commandText.Replace("@" + param.Name, "'" + param.Value + "'");
                }
            }
            return commandText;
        }

        /// <summary>
        /// 转化为ObjectParameter可变参数
        /// </summary>
        /// <param name="listfilter"></param>
        /// <returns></returns>
        public static ObjectParameter[] ConvertToListObjParam(IEnumerable<FilterParam> listfilter)
        {
            var list = new List<ObjectParameter>();
            foreach (var param in listfilter)
            {
                list.Add(param.ToObjParam());
            }
            return list.ToArray();
        }
    }
}